export default function (options = {}) {
  const { root, errorIcon } = options;

  let io = new IntersectionObserver((entries) =>{
    entries.forEach(item => {
      // isIntersecting是一个Boolean值，判断目标元素当前是否可见
      if (item.isIntersecting) {
        const box = item.target;
        const { url, size, color } = box.dataset;

        const image = new Image();
        image.src = url;

        image.onload = () => {
          box.innerHTML = `<img style="width: 100%; height: 100%" src="${ url }" />`;
        }

        image.onerror = () => {
          box.innerHTML = `<div style="font-size: ${size}; color: ${ color }" class="error ${ errorIcon }"></div>`;
        }

        // 图片加载后即停止监听该元素
        io.unobserve(item.target)
      }
    })
  }, {
    root: document.querySelector(root)
  })

  return {
    mounted(el, binding, vnode) {
      el.dataset.url = binding.value;

      // observe遍历监听所有img节点
      io.observe(el);
      //  遍历收集到的数据， 并对对其进行监听，判断是否满足加载条件
     },
    // 绑定元素的父组件卸载后调用
    unmounted(el, binding, vnode) { }
  }

}